package com.cedifie.lendapp.ui.steps.fm

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.FmStepOcrPassportBinding
import com.cedifie.lendapp.http.ApiService
import com.cedifie.lendapp.http.ApiService.addCommonParams
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.ui.steps.act.CedCameraOcrAct
import com.cedifie.lendapp.ui.steps.act.CedOcrUploadAct
import com.cedifie.lendapp.ui.steps.act.CedStepAct
import com.cedifie.lendapp.utils.dialog.PhotoDialog
import com.cedifie.lendapp.utils.event.CedEventData
import com.cedifie.lendapp.utils.event.CedEventManager
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.imagecovert.ImageConvert
import com.lib.base.base.BaseFragment
import com.lib.base.utils.ImageUtil
import com.lib.base.utils.log.LogHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/20 17:59
 * @Annotation：Ocr - 护照
 */
class CedOcrPassportFm: BaseFragment() {
    private var _binding: FmStepOcrPassportBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )
    //正面照
    private var imgFrontUrl = ""
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    override fun getCedRootView(inflater: LayoutInflater): View {
        _binding = FmStepOcrPassportBinding.inflate(inflater)
        return binding.root
    }

    override fun initCedView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))

        EventBus.getDefault().register(this)
        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = requireContext(), uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        launch(Dispatchers.Main){
                            delay(200)
                            CedOcrUploadAct.start(requireContext(),"PASSPORT",localPath)
                        }
                    }
                }
            } else {
                LogHelper.e("No media selected")
            }
        }
    }

    override fun initCedListener() {
        //驾驶证证正面
        _binding?.frontLayout?.setOnClickListener {
            showPhotoDialog("Passport")
        }

        //下一步
        _binding?.btnNext?.setOnClickListener {
            if (imgFrontUrl.isEmpty()){
                showCedToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_OCR_PASSPORT_NEXT,"")
            //立即上报
            CedEventManager.getInstance().updateCedEventsNow()

            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.CED_API_OCR_INFO_PATH)
                put("cardType","PASSPORT")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("cardImgUrl",imgFrontUrl)//证件图片正面
            }
            val act = context as CedStepAct
            act.onSubmitProcessAction(params)
        }
    }

    override fun initCedData() {
        HttpHelper.addCedEventAction(String.format(CedEventType.PAGE.CED_PAGE_STEP_OCR_XX_START,"Passport"),"")
    }

    /**
     * 收到使用照片通知
     */
    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onCedUserPhotoReceive(data: CedEventData){
        if (data.eventType == CedEventData.TYPE.CED_USE_PHOTO){
            //图片网络地址
            val imgUrl = data.eventData.optString("imgUrl")
            //图片本地地址
            val imgPath = data.eventData.optString("imgPath")
            LogHelper.e(">>>>>>>>>>>>>>>>>>>>>>>>>>>>user photo imgUrl ： $imgUrl")
            imgFrontUrl = imgUrl
            _binding?.let {
                ImageUtil.instance?.loadImageUrl(requireContext(),it.imgView,imgPath)
            }
        }
    }

    /**
     * 相机、相册选择
     */
    private fun showPhotoDialog(eventRemark: String){
        val photoDialog = PhotoDialog(context,eventRemark,object : PhotoDialog.IDialogCallback{
            override fun openCamera() {
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_CAMERA,eventRemark)
                onOpenCamera()
            }
            override fun openAlbum() {
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_ALBUM,eventRemark)
                onOpenAlbum()
            }
        })
        photoDialog.show()
    }

    /**
     * 打开相机
     */
    private fun onOpenCamera(){
        CedCameraOcrAct.start(requireContext(),"PASSPORT")
    }

    /**
     * 打开相册
     */
    private fun onOpenAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        HttpHelper.addCedEventAction(String.format(CedEventType.PAGE.CED_PAGE_STEP_OCR_XX_END,"Passport"),"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}